package com.kaibes.im.view.fragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.NotificationManagerCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;

import com.kaibes.im.R;
import com.kaibes.im.model.NotificationInterpreter;
import com.kaibes.im.model.SocketWorker;
import com.kaibes.im.model.adapter.ContactListviewAdapter;
import com.kaibes.im.model.adapter.ConversationListviewAdapter;
import com.kaibes.im.model.adapter.PluginListviewAdapter;
import com.kaibes.im.model.data.AlertDialogData;
import com.kaibes.im.model.data.PluginListviewData;
import com.kaibes.im.model.hanlder.BaseHandler;
import com.kaibes.im.view.RoundImageView;
import com.kaibes.im.view.listview.ContactListview;
import com.kaibes.im.view.listview.ConversationListview;
import com.kaibes.im.view.listview.ConversationListview.OnDismissCallback;
import com.kaibes.im.view.listview.PluginListview;

public class MainFragment extends KaibesFragment implements OnClickListener,
	OnItemClickListener {

    public static final int REFRESH_CONTACTS = 0x1;
    public static final int REFRESH_CONVERSATION = 0x2;
    public static final int REFRESH_PLUGIN = 0x3;
    public static final int REFRESH_USER_IMAGE_VIEW = 0x4;
    public static final int REFRESH_NOTIFICATION = 0x5;

    public static final int NOTIFICATION_NOTIFICATION = 0X1;
    public static final int NOTIFICATION_MESSAGE = 0X2;

    private ContactListview contactsListView;
    private ConversationListview conversationListView;
    private PluginListview pluginListview;
    private TabHost tabHost;

    private RoundImageView userImageView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    Bundle savedInstanceState) {
	getKaibesActivity().getProgressDialogData().reset().setTitle("载入中")
		.setMessage("正在载入数据。。。");
	getKaibesActivity().showProgressDialog();

	View rootView = inflater.inflate(R.layout.fragment_main, container,
		false);
	// 初始化conversation
	userImageView = (RoundImageView) rootView
		.findViewById(R.id.ivConversationTitleLeft);

	if (getKaibesActivity().getKaibesApplication().getUserPhotoBitmap() != null) {
	    userImageView.setImageBitmap(getKaibesActivity()
		    .getKaibesApplication().getUserPhotoBitmap());
	    userImageView.setTag(false);
	} else {
	    userImageView.setTag(true);
	}

	conversationListView = (ConversationListview) rootView
		.findViewById(R.id.conversationListview);

	conversationListView.setAdapter(new ConversationListviewAdapter(
		getKaibesActivity(), getKaibesActivity().getKaibesApplication()
			.getConversationFragmentDatas()));
	conversationListView.setOnDismissCallback(new OnDismissCallback() {

	    @Override
	    public void onDismiss(BaseAdapter baseAdapter, int position) {
		((ConversationListviewAdapter) baseAdapter).getDatas().remove(
			position - 1);
	    }
	});

	// 初始化contact
	contactsListView = (ContactListview) rootView
		.findViewById(R.id.contactListview);
	contactsListView.setAdapter(new ContactListviewAdapter(
		getKaibesActivity(), getKaibesApplication()
			.getContactFragmentDatas()));

	// 初始化plugin
	pluginListview = (PluginListview) rootView
		.findViewById(R.id.pluginListview);
	pluginListview
		.setAdapter(new PluginListviewAdapter(getKaibesActivity()));

	setHandler(new BaseHandler<MainFragment>(this) {

	    public void handleMessage(Message msg) {
		switch (msg.what) {
		case REFRESH_CONTACTS: {
		    getData().contactsListView.getBaseAdapter()
			    .notifyDataSetChanged();
		    break;
		}

		case REFRESH_CONVERSATION: {
		    getData().conversationListView.getBaseAdapter()
			    .notifyDataSetChanged();
		}
		    break;

		case REFRESH_PLUGIN: {
		    getData().pluginListview.getBaseAdapter()
			    .notifyDataSetChanged();
		}
		    break;

		case REFRESH_USER_IMAGE_VIEW: {
		    if (getData().getKaibesApplication().getUserPhotoBitmap() != null) {
			getData().userImageView.setImageBitmap(getData()
				.getKaibesApplication().getUserPhotoBitmap());
		    }
		}
		    break;
		case REFRESH_NOTIFICATION: {
		    if (!tabHost.getCurrentTabTag().equals("plugin")) {
			tabHost.setCurrentTabByTag("plugin");
		    }
		}
		    break;

		case KaibesFragment.REFRESH_FRAGMENT: {
		    refresh(REFRESH_CONVERSATION);
		    refresh(REFRESH_CONTACTS);
		    refresh(REFRESH_PLUGIN);
		}
		    break;

		default:
		    break;
		}
	    };

	});

	return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
	initTabHost();

	// conversation
	conversationListView.setOnItemClickListener(this);

	// contact
	contactsListView.setOnItemClickListener(this);
	getView().findViewById(R.id.btnMainContactAdd).setOnClickListener(this);

	// plugin
	pluginListview.setOnItemClickListener(this);

	getKaibesActivity().closeProgressDialog();

	if (getKaibesApplication().getPluginListviewDatas().size() > 0) {
	    getKaibesApplication().getSoundPoolUtil().play(0);
	    getKaibesApplication().refresh(KaibesFragment.MAIN_FRAGMENT,
		    MainFragment.REFRESH_NOTIFICATION);
	}
	super.onActivityCreated(savedInstanceState);
    }

    @Override
    public boolean onBackPressed() {
	exitApp();
	return false;
    }

    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	case R.id.btnMainContactAdd:
	    getKaibesActivity().changeFragment(ContactAddFragment.class);
	    break;

	default:
	    break;
	}
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
	    long id) {
	switch (parent.getId()) {
	case R.id.conversationListview: {
	    String chatFragmentData = (String) parent.getAdapter().getItem(
		    position);
	    getKaibesActivity().getKaibesApplication().setCurentContact(
		    chatFragmentData);
	    getKaibesActivity().changeFragment(ChatFragment.class);

	    NotificationManagerCompat manager = NotificationManagerCompat
		    .from(getKaibesActivity());
	    manager.cancel(SocketWorker.notification_id);
	}
	    break;

	case R.id.contactListview: {
	    String contactInformationData = (String) parent.getAdapter()
		    .getItem(position);
	    getKaibesActivity().getKaibesApplication().setCurentContact(
		    contactInformationData);
	    getKaibesActivity()
		    .changeFragment(ContactInformationFragment.class);
	    break;
	}

	case R.id.pluginListview: {
	    final PluginListviewData pluginListviewData = (PluginListviewData) parent
		    .getAdapter().getItem(position);
	    dealWithNotificationData(pluginListviewData);
	}
	    break;

	default:
	    break;
	}

    }

    @Override
    protected void reset() {
	if ((boolean) userImageView.getTag()
		&& getKaibesActivity().getKaibesApplication()
			.getUserPhotoBitmap() != null) {
	    userImageView.setImageBitmap(getKaibesActivity()
		    .getKaibesApplication().getUserPhotoBitmap());
	    userImageView.setTag(false);
	}
	contactsListView.getBaseAdapter().notifyDataSetChanged();
	conversationListView.getBaseAdapter().notifyDataSetChanged();
    }

    @SuppressLint("InflateParams")
    private void initTabHost() {
	tabHost = (TabHost) getView().findViewById(R.id.mainTabHost);
	tabHost.setup();
	tabHost.setOnTabChangedListener(new OnTabChangeListener() {

	    @Override
	    public void onTabChanged(String tabId) {
		if (tabId.equals("contact")) {
		    refresh(REFRESH_CONTACTS);
		}

		if (tabId.equals("conversation")) {
		    refresh(REFRESH_CONVERSATION);
		}

		if (tabId.equals("plugin")) {
		    refresh(REFRESH_PLUGIN);
		}
	    }
	});

	TabSpec spec1 = tabHost.newTabSpec("conversation");
	TabSpec spec2 = tabHost.newTabSpec("contact");
	TabSpec spec3 = tabHost.newTabSpec("plugin");

	spec1.setContent(R.id.tabConversation);
	spec2.setContent(R.id.tabContact);
	spec3.setContent(R.id.tabPlugin);

	spec1.setIndicator(LayoutInflater.from(getActivity()).inflate(
		R.layout.tab_main_widget_conversation, null));
	spec2.setIndicator(LayoutInflater.from(getActivity()).inflate(
		R.layout.tab_main_widget_contact, null));
	spec3.setIndicator(LayoutInflater.from(getActivity()).inflate(
		R.layout.tab_main_widget_plugin, null));

	tabHost.addTab(spec1);
	tabHost.addTab(spec2);
	tabHost.addTab(spec3);
    }

    private void removeNotification(final PluginListviewData pluginListviewData) {
	getKaibesApplication().getPluginListviewDatas().remove(
		pluginListviewData);
	getKaibesActivity().refresh(KaibesFragment.MAIN_FRAGMENT,
		REFRESH_PLUGIN);
    }

    public void dealWithNotificationData(
	    final PluginListviewData pluginListviewData) {
	AlertDialogData alertData = getKaibesActivity().getAlertDialogData()
		.reset().setTitle(pluginListviewData.getContactname())
		.setMessage(pluginListviewData.getMessage());

	if (pluginListviewData.getAction() == NotificationInterpreter.ACTION_MESSAGE) {
	    alertData.setPositiveString("确定").setPositiveListener(
		    new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
			    removeNotification(pluginListviewData);
			}
		    });
	} else {
	    alertData
		    .setPositiveString("允许")
		    .setPositiveListener(new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			    getKaibesApplication().sendData(1,
				    SocketWorker.ACTION_NOTIFICATION,
				    pluginListviewData.getId(), true);

			    removeNotification(pluginListviewData);

			    try {
				getKaibesApplication()
					.sendData(
						1,
						SocketWorker.ACTION_CONTACTS,
						new JSONArray().put(new JSONObject()
							.put("contactname",
								pluginListviewData
									.getContactname())));
			    } catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			    }

			}
		    }).setNegativeString("拒绝")
		    .setNegativeListener(new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
			    getKaibesActivity().getKaibesApplication()
				    .sendData(1,
					    SocketWorker.ACTION_NOTIFICATION,
					    pluginListviewData.getId(), false);
			    removeNotification(pluginListviewData);
			}

		    });
	}
	NotificationManagerCompat manager = NotificationManagerCompat
		.from(getKaibesActivity());
	manager.cancel(NotificationInterpreter.notification_id);
	getKaibesActivity().showAlertDialog();
    }

    // ---------------------------GET AND SET 1--------------------------
    public TabHost getTabHost() {
	return tabHost;
    }

}
